package com.tongzhan.util;

import com.tongzhan.base.Consts;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.SocketException;
import java.util.Calendar;

public class FtpUtil {

    private static Logger logger = Logger.getLogger(FtpUtil.class);

    private FTPClient ftpClient;
    //从本地文件获取各种属性
//    public static String ftpIP= "192.168.1.89";
//    public static Integer ftpPort= 21;
//    public static String ftpUserName= "admin";
//    public static String ftpPassword= "admin";
//    public static String ftpEncode = "GBK";

    public FtpUtil() {

    }

    public synchronized boolean connectServer() {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding(Consts.ftpEncode);//解决上传文件时文件名乱码
        int reply = 0 ;
        try {
            // 连接至服务器
            ftpClient.connect(Consts.ftpIP, Consts.ftpPort);
            // 登录服务器
            ftpClient.login(Consts.ftpUserName, Consts.ftpPassword);
            //登陆成功，返回码是230
            reply = ftpClient.getReplyCode();
            // 判断返回码是否合法
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return false;
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }

    //判断ftp服务器文件是否存在
    public boolean existFile(String path)  {
        boolean flag = false;
        FTPFile[] ftpFileArr;
        try {
            ftpFileArr = ftpClient.listFiles(path);
            if (ftpFileArr.length > 0) {
                flag = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    //删除ftp文件
    public synchronized boolean deleteFile(String pathname, String filename){
        boolean flag = false;
        try {
            System.out.println("开始删除文件");
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    public synchronized boolean upload(InputStream inputStream , String fileName , String path) {
        try {

            //切换工作路径，设置上传的路径
            ftpClient.changeWorkingDirectory(path);
            //设置1M缓冲
            ftpClient.setBufferSize(1024);
            // 设置被动模式
            ftpClient.enterLocalPassiveMode();
            // 设置以二进制方式传输
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            /*
             * 第一个参数：服务器端文档名
             * 第二个参数：上传文档的inputStream
             * 在前面设置好路径，缓冲，编码，文件类型后，开始上传
             */
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            closeClient();
        }

    }

    public boolean checkSubfolder(String path, String subfolderName) {
        try {
            //切换到FTP根目录
            ftpClient.changeWorkingDirectory(path);
            //查看根目录下是否存在该文件夹
            InputStream is = ftpClient.retrieveFileStream(new String(subfolderName.getBytes("UTF-8")));
            if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
                //若不存在该文件夹，则创建文件夹
                return createSubfolder(path,subfolderName);
            }
            if (is != null) {
                is.close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public synchronized boolean createSubfolder(String path,String subfolderName){
        try {

            String[] dirs = subfolderName.split("/");
            for (String dir : dirs) {
                boolean res = ftpClient.changeWorkingDirectory(path);
                System.out.println(res);
                if (null == dir || "".equals(dir)) continue;
                path += "/" + dir;
                ftpClient.makeDirectory(dir);
//                if (!ftpClient.changeWorkingDirectory(tempPath)) {
//                    if (!ftpClient.makeDirectory(dir)) {
//                        return true;
//                    } else {
//                        ftpClient.changeWorkingDirectory(tempPath);
//                    }
//                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

   public boolean createDir(String remote) throws Exception{

    String directory = remote.substring(0, remote.lastIndexOf("/") + 1);

    if(!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))) {

        // 如果远程目录不存在，则递归创建远程服务器目录
        int start = 0;
        int end = 0;
        if(directory.startsWith("/")){
            start = 1;
        } else{
            start = 0;
        }
        end = directory.indexOf("/",start);
        while(true){
            String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
            if(!ftpClient.changeWorkingDirectory(subDirectory)){
                if(ftpClient.makeDirectory(subDirectory)){
                ftpClient.changeWorkingDirectory(subDirectory);
                } else {
                System.out.println("创建目录失败");
                }
            }
                start = end + 1;
                end=directory.indexOf("/",start);
                if(end<=start){
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 断开与远程服务器的连接
     */
    public void closeClient(){
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 服务器上传文件日期目录
     * @return
     */
    public String getDay() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day =calendar.get(Calendar.DATE);
        StringBuilder s = new StringBuilder();
        s.append("/").append(year).append("/").append(month).append("/").append(day).append("/");
        return s.toString();
    }

        /* Description: 从FTP服务器下载文件
         * @param url FTP服务器hostname
         * @param port FTP服务器端口
         * @param username FTP登录账号
         * @param password FTP登录密码
         * @param remotePath FTP服务器上的相对路径
         * @param fileName 要下载的文件名
         * @param localPath 下载后保存到本地的路径
         * @return
         */
        public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {
            boolean success = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(url, port);
                //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
                ftp.login(username, password);//登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return success;
                }
                ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
                FTPFile[] fs = ftp.listFiles();
                for(FTPFile ff:fs){
                    if(ff.getName().equals(fileName)){
                        File localFile = new File(localPath+"/"+ff.getName());

                        OutputStream is = new FileOutputStream(localFile);
                        ftp.retrieveFile(ff.getName(), is);
                        is.close();
                    }
                }

                ftp.logout();
                success = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return success;
        }
    }
